package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 定时任务类，自动删除垃圾图片
 */
@Component
@Slf4j
public class ImgTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil AliOssUtil;

//    @Scheduled(cron = "*/20 * * * * ?")
    // TODO 这里为了方便编码先注释掉，记得打开
    @Transactional
    public void deleteImg() {
        log.info("开始删除垃圾图片");

        //1.获取集合的操作接口
        SetOperations setOperations = redisTemplate.opsForSet();
        //2.对比redis中的所有图片和数据库中的图片,获取差值集合
        Set<String> diffImgs = setOperations.difference("SETMEAL_IMG", "SETMEAL_IMG_DB_RESOURCES");
        for (String diffImg : diffImgs) {
            log.info("删除垃圾图片：{}", diffImg);
            //3.从redis中删除
            setOperations.remove("SETMEAL_IMG", diffImg);
            log.info("删除redis成功");
            //4.从oss中删除
            AliOssUtil.delete(diffImg);
            log.info("删除阿里云成功");
        }
    }
}
